package com.hj.service.fileserver.impl;

import com.hj.service.fileserver.FileServer;
import com.hj.util.FileUniqueIdUtils;
import com.hj.util.MinioUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dehui dou
 * @date 2020/10/3 18:02
 * @description
 */
@Service("minIOServerImpl")
public class MinIOServerImpl implements FileServer {
    private static Logger logger = LoggerFactory.getLogger(MinIOServerImpl.class);

    /**
     * @author dehui dou
     * @description 文件上传
     * @param file
     * @param fileExtName
     * @param params
     * @return java.lang.String
     */
    @Override
    public String upload(MultipartFile file, String fileExtName, Map<String, String> params) {
        Map<String, String> metaList = null;
        if (params != null) {
            metaList = new ConcurrentHashMap<>();
            metaList.put("systemCode", params.get("systemCode"));
            metaList.put("fileName", params.get("fileName"));
            metaList.put("filePath", params.get("filePath"));
            metaList.put("fileSize", params.get("fileSize"));
            metaList.put("createTm", params.get("createTm"));
        }
        String fileUniqueId = FileUniqueIdUtils.getFileUniqueId(null);
        String fileName = String.format("%s.%s", fileUniqueId, fileExtName);
        MinioUtil.uploadFile(file, fileName, metaList);
        return fileName;
    }

    /**
     * @author dehui dou
     * @description
     * @param fileId
     * @return byte[]
     */
    @Override
    public byte[] download(String fileId) {
        byte[] fileData = null;
        try {
            fileData = MinioUtil.downloadFile(fileId);
        } catch (Exception e) {
            logger.error(String.format("文件下载失败 msg:%s", fileId), e);
        }
        return fileData;
    }
}
